package com.autodatabase.util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.autodatabase.model.FactoryItemInfo;

public class WebRequestUtil {
	/**
	 * 通过request获得页面上post的数据，并生成所传对象实例
	 * @param cls
	 * @param request
	 * @return
	 */
	public static Object parseObj(Class cls, HttpServletRequest request) {
		Method[] methods = cls.getMethods();
		Map pmap = request.getParameterMap();
		Map<Method, String> instanceMap = new HashMap<Method, String>();

		for(Method method : methods) {
			String mname = method.getName();

			if(mname.startsWith("set") && mname.length() >= 4) {
				String p = mname.substring(4);
				String f = mname.substring(3, 4);
				f = f.toLowerCase();
				p = f + p;
				Object value = pmap.get(p);

				if(value instanceof String[]) {
					String[] val = (String[]) value;
					
					if(val.length == 0) {
						continue;
					}

					String realVal = val[0];
					instanceMap.put(method, realVal);
				}
			}
		}

		try {
			Object obj = cls.newInstance();

			for(Method m : instanceMap.keySet()) {
				Class[] ptypes = m.getParameterTypes();

				if(ptypes.length > 0) {
					Class ptype = ptypes[0];
					Object value = null;
					
					if(String.class.equals(ptype)) {
						value = instanceMap.get(m);
					}
					else if(Integer.class.equals(ptype) || int.class.equals(ptype)) {
						try {
							value = Integer.parseInt(instanceMap.get(m));
						}
						catch(Exception e) {
						}
					}

					m.invoke(obj, value);
				}
			}

			return obj;
		} 
		catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 提取DatabaseInfo信息
	 * @param request
	 */
	public static FactoryItemInfo parseFactoryItem(HttpServletRequest request) {
		return (FactoryItemInfo) parseObj(FactoryItemInfo.class, request);
	}
}
